package club.ruanx.auth.config;

import club.ruanx.auth.filter.JwtAuthenticationFilter;
import club.ruanx.auth.vcode.config.ValidateCodeSecurityConfig;
import club.ruanx.security.provider.AbstractAuthenticationLoginFilterProvider;
import club.ruanx.security.provider.AuthorizeConfigProviderManager;
import club.ruanx.security.provider.BaseDetailsAuthenticationProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author 阮胜
 * @date 2018/8/4 15:53
 */
@Configuration
@EnableWebSecurity
@Slf4j
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final PasswordEncoder passwordEncoder;
    private final AuthorizeConfigProviderManager authorizeConfigProviderManager;
    private final Map<String, AbstractAuthenticationLoginFilterProvider> loginFilterProviderMap;
    private final ValidateCodeSecurityConfig validateCodeSecurityConfig;

    public SecurityConfig(PasswordEncoder passwordEncoder, AuthorizeConfigProviderManager authorizeConfigProviderManager, Map<String, AbstractAuthenticationLoginFilterProvider> loginFilterProviderMap, ValidateCodeSecurityConfig validateCodeSecurityConfig) {
        this.passwordEncoder = passwordEncoder;
        this.authorizeConfigProviderManager = authorizeConfigProviderManager;
        this.loginFilterProviderMap = loginFilterProviderMap;
        this.validateCodeSecurityConfig = validateCodeSecurityConfig;
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        for (AbstractAuthenticationLoginFilterProvider abstractAuthenticationLoginFilterProvider : loginFilterProviderMap.values()) {
            BaseDetailsAuthenticationProvider userDetailsAuthenticationProvider = abstractAuthenticationLoginFilterProvider.obtainDetailsAuthenticationProvider();
            userDetailsAuthenticationProvider.setPasswordEncoder(passwordEncoder);
            userDetailsAuthenticationProvider.setUserDetailsService(abstractAuthenticationLoginFilterProvider.obtainUserDetailsService());
            auth.authenticationProvider(userDetailsAuthenticationProvider);
        }
    }


    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        //httpSecurity.apply(validateCodeSecurityConfig); 开启验证码过滤器
        authorizeConfigProviderManager.configure(httpSecurity.authorizeRequests());
        for (AbstractAuthenticationLoginFilterProvider abstractAuthenticationLoginFilterProvider : loginFilterProviderMap.values()) {
            JwtAuthenticationFilter filter = new JwtAuthenticationFilter(abstractAuthenticationLoginFilterProvider.obtainLoginUrl(),
                    authenticationManager(), abstractAuthenticationLoginFilterProvider.tokenGenerator());
            filter.setAuthenticationSuccessHandler(abstractAuthenticationLoginFilterProvider.getSuccessHandler());
            filter.setAuthenticationFailureHandler(abstractAuthenticationLoginFilterProvider.getFailureHandler());
            httpSecurity
                    .addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class);
        }
        //手动实现的权限验证管理器
        httpSecurity
                .csrf().disable()
                .logout().disable()
                .formLogin().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .anonymous()
                .and()
                .exceptionHandling().authenticationEntryPoint(
                (req, rsp, e) -> rsp.sendError(HttpServletResponse.SC_UNAUTHORIZED)
        ).and().authorizeRequests();
    }
}
